package test;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class demo11UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp = null;
    private int serverPort = 0;
    public demo11UdpEchoClient(String ip, int port) throws SocketException {
        this.serverIp = ip;
        this.serverPort = port;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("客户端启动");
        while (true){
            //获取客户端的需求
            System.out.println("->");
            String request = sc.next();
            //将需求发送到服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //接收响应
            DatagramPacket respondPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respondPacket);
            //将响应输出到控制台
            String respond = new String(respondPacket.getData(), 0, respondPacket.getLength());
            System.out.println(respond);
        }
    }

    public static void main(String[] args) throws IOException {
        demo11UdpEchoClient demo8TcpEchoClient = new demo11UdpEchoClient("127.0.0.1", 9090);
        demo8TcpEchoClient.start();
    }
}
